import React, { Component } from 'react';

import axios from 'axios'
import Api from '../config/api'

import style from './scss/login.scss'

import Button from 'antd/lib/button'
import Form from 'antd/lib/form'
import Input from 'antd/lib/input'
import Icon from 'antd/lib/icon'
import Modal from 'antd/lib/modal'

const FormItem = Form.Item;
axios.defaults.withCredentials = true;

class LoginForm extends Component {
    constructor(props) {
        super(props);
        this.state = {
            showVerifyModal: false,
            showCount: false,
            countTime: 60,
            captcha: Api['captcha'],
            captchaRandom: 'a',
            verifyText: '您登录的是外网，需要验证！',
            userPhone: '',
            logining: false
        }
    }
    //登录提交
    handleSubmit(e) {
        e.preventDefault();
        this.props.form.validateFields(['userName', 'password'], (err, values) => {
            if (!err) {
                let param = 'account=' + values.userName + '&password=' + values.password;
                axios.post(Api['login'], param).then((res) => {
                    if (res && res.code === '1') {
                        let data = JSON.parse(JSON.stringify(res.data))
                        this.setState({
                            logining: true
                        })
                        if (data.menu.length === 0) {
                            document.location.pathname = '/noAuth'
                        } else {
                            //localStorage存入菜单和用户数据
                            localStorage.setItem('menu', JSON.stringify(data.menu))
                            localStorage.setItem('userInfo', JSON.stringify(data.user))
                            setTimeout(() => { this.props.toMain() }, 1000);
                        }
                    }
                    else if (res && res.code === '2002') {
                        this.setState({
                            showVerifyModal: true,
                            userPhone: res.data.data,
                            logining: false
                        })
                    }
                    else {
                        this.setState({
                            logining: false
                        })
                    }
                }).catch((error) => {
                    console.log(error)
                })
            }
        })
    }
    handleCount() {
        this.props.form.validateFields(['tuxing'], (err, values) => {
            if (!err) {
                axios.post(Api['sendCodeMessage'] + '?captcha=' + this.tuxingInput.input.value).then((res) => {
                    if (res && res.code === '1') {
                        this.setState({
                            showCount: true,
                            verifyText: `验证码已发送到${this.state.userPhone}，请注意查收！`
                        })
                        this.intervalC = setInterval(() => {
                            let time = this.state.countTime;
                            if (!this.state.countTime) {
                                clearInterval(this.intervalC);
                                this.setState({
                                    showCount: false,
                                    countTime: 60
                                })
                            }
                            else {
                                time -= 1;
                                this.setState({
                                    countTime: time
                                })
                            }
                        }, 1000)
                    }
                    else if (res && res.code === '2003') {
                        this.props.form.resetFields(['tuxing'])
                        this.changeCaptcha();
                    }
                }).catch((error) => {
                    console.log(error)
                })
            }
        })
    }
    //更改查询字符串使验证码改变
    changeCaptcha() {
        this.setState({
            captcha: Api['captcha'] + '?' + this.state.captchaRandom,
            captchaRandom: this.state.captchaRandom === 'a' ? 'b' : 'a'
        })
    }
    handleVerify() {
        this.props.form.validateFields(['tuxing', 'msgtext'], (err, values) => {
            if (!err) {
                axios.post(Api['submitMessageCode'] + '?msgCode=' + this.msgTestInput.input.value).then((res) => {
                    if (res) {
                        let data = JSON.parse(JSON.stringify(res.data))
                        if (data.menu.length === 0) {
                            document.location.pathname = '/noAuth'
                        } else {
                            localStorage.setItem('menu', JSON.stringify(data.menu))
                            localStorage.setItem('userInfo', JSON.stringify(data.user))
                            setTimeout(() => { this.props.toMain() }, 1000);
                        }
                    }
                }).catch((error) => {
                    console.log(error)
                })
            }
        })
    }
    handleCancel() {
        this.props.form.resetFields(['tuxing', 'msgtext'])
        this.setState({
            showVerifyModal: false
        })
    }
    render() {
        const { getFieldDecorator } = this.props.form;
        return (
            <div>
                <Form onSubmit={this.handleSubmit.bind(this)} className={style.loginform}>
                    <FormItem>
                        {getFieldDecorator('userName', { rules: [{ required: true, message: '请输入用户名' }] })(<Input style={{ height: '42px' }} prefix={<Icon type="user" style={{ color: 'rgba(0,0,0,.25)' }} />} placeholder="Username" />)}
                    </FormItem>
                    <FormItem>
                        {getFieldDecorator('password', { rules: [{ required: true, message: '请输入密码' }] })(<Input style={{ height: '42px' }} type="password" prefix={<Icon type="lock" style={{ color: 'rgba(0,0,0,.25)' }} />} placeholder="Password" />)}
                    </FormItem>
                    <FormItem>
                        <Button className={style['login-btn']} disabled={this.state.logining} type="primary" htmlType="submit">{this.state.logining ? '登录中...' : '登录'}</Button>
                    </FormItem>
                </Form>
                <Modal width={370} visible={this.state.showVerifyModal} onCancel={this.handleCancel.bind(this)} wrapClassName="vertical-center-modal" title="验证" footer={[
                    <Button key="sure" type="primary" onClick={this.handleVerify.bind(this)}>确定</Button>,
                    <Button key="cancel" type="danger" onClick={this.handleCancel.bind(this)}>取消</Button>
                ]} >
                    <Form className={style["verify-form"]}>
                        <span style={{ color: 'red' }}>{this.state.verifyText}</span>
                        <FormItem>
                            {getFieldDecorator('tuxing', { rules: [{ required: true, message: '必填' }] })(<Input className={style.tuxingTest} ref={(input) => { this.tuxingInput = input }} style={{ height: '45px' }} placeholder="请输入图形验证码" />)}
                            <img className={style.tuxingTestImg} onClick={this.changeCaptcha.bind(this)} src={this.state.captcha} alt="tuxing" />
                        </FormItem>
                        <FormItem>
                            {getFieldDecorator('msgtext', { rules: [{ required: true, message: '必填' }] })(<Input className={style.msgTest} ref={(input) => { this.msgTestInput = input }} style={{ height: '45px' }} placeholder="请输入短信验证码" />)}
                            {!this.state.showCount ? <Button className={style.msgTestBtn} type="primary" onClick={this.handleCount.bind(this)}>获取短信验证码</Button> : <Button className={style.msgTestBtn} disabled onClick={this.handleCount.bind(this)}>({this.state.countTime})秒后重新获取</Button>}
                        </FormItem>
                    </Form>
                </Modal>
            </div>
        )
    }
}

const ValidateLoginForm = Form.create()(LoginForm);

class Login extends Component {
    constructor(props) {
        super(props)
        this.resizeWindow = this.resize.bind(this)
        this.state = {
            cheight: document.documentElement.clientHeight + 'px',
        }
    }
    componentDidMount() {
        console.log(process.env.NODE_ENV)
        window.addEventListener('resize', this.resizeWindow)
    }
    componentWillUnmount() {
        window.removeEventListener('resize', this.resizeWindow)
    }
    resize() {
        this.setState({
            cheight: document.documentElement.clientHeight + 'px'
        })
    }
    toMain() {
        this.props.history.replace("/main");
    }
    render() {
        return (
            <div className={style['login-container']} style={{ height: this.state.cheight, overflow: 'hidden' }}>
                <div className={style['login-header']}>
                    <img src={require('../assets/youyu-logo.png')} alt="youyu-logo" />
                    <span>展奎短信服务平台</span>
                </div>
                <img className={style["login-big-img"]} src={require('../assets/login-big-img.png')} alt="login-img" />
                <div className={style["login-box"]}>
                    <div className={style["login-form-box"]}>
                        <h1>账号登录</h1>
                        <ValidateLoginForm toMain={this.toMain.bind(this)} />
                    </div>
                </div>
                <div className={style["login-footer"]}>
                    <span>Copyright © 上海展奎科技有限公司</span>
                </div>
            </div>
        )
    }
}

export default Login